package convert.converter;


import com.opencsv.CSVWriter;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class xml_to_csv {

    public static void main(String[] args) {
        String xmlFilePath = "src/resource/xml/input.xml";
        String csvFilePath = "src/resource/csv/xml_output.csv";

        convertXMLToCSV(xmlFilePath, csvFilePath);
    }

    public static void convertXMLToCSV(String xmlFilePath, String csvFilePath) {
        try {
            DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
            DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
            Document document = documentBuilder.parse(new File(xmlFilePath));

            Element rootElement = document.getDocumentElement();
            NodeList nodeList = rootElement.getChildNodes();
            List<List<String>> dataList = new ArrayList<>();

            for (int i = 0; i < nodeList.getLength(); i++) {
                Node node = nodeList.item(i);
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    List<String> rowData = new ArrayList<>();
                    NodeList childNodes = element.getChildNodes();
                    for (int j = 0; j < childNodes.getLength(); j++) {
                        Node childNode = childNodes.item(j);
                        if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                            rowData.add(childNode.getTextContent());
                        }
                    }
                    dataList.add(rowData);
                }
            }

            CSVWriter csvWriter = new CSVWriter(new FileWriter(csvFilePath));
            for (List<String> rowData : dataList) {
                csvWriter.writeNext(rowData.toArray(new String[0]));
            }
            csvWriter.close();

            System.out.println("XML to CSV conversion completed successfully.");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
